package com.hc.server.actions;

import java.util.Iterator;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.json.JSONArray;
import org.json.JSONObject;

import com.hc.server.Config;
import com.hc.server.IAction;
import com.hc.server.Request;
import com.hc.server.Response;
import com.hc.server.db.Canton;
import com.hc.server.db.DBFactory;

/**
 * 获取城市列表
 * @author xujh
 *
 */
public class GET_CITYS implements IAction {

	private static final String VERSION = "VER";
	private static final String CITYS = "CITYS";
	
	private static final String INDEX = "INDEX";
	private static final String NAME = "NAME";
	private static final String CODE = "CODE";
	private static final String HOT = "热";
	private static final String[] INDEX_KEY = {"A","B","C","D","E","F","G","H","I","J","K","L","M","N","O","P","Q","R","S","T","U","V","W","X","Y","Z"};
	
	private static JSONObject curCitys = null;
	
	@SuppressWarnings("unchecked")
	@Override
	public void execute(Request req, Response resp) {
		int ver = req.optIntArg(VERSION);
		JSONObject citys = new JSONObject();
		JSONArray index = new JSONArray();
		if(ver < Config.CITY_VER){
			if(null == curCitys){
				Session session = DBFactory.openSession();
				Transaction t = session.beginTransaction();
				try{
					t.begin();
					String recommendHql = "from Canton as canton where canton.isRecommend = 1";
					Query query = session.createQuery(recommendHql);
					Iterator<Canton> recommends = query.iterate();
					JSONArray array = new JSONArray(); 
					while( recommends.hasNext() ){
						JSONObject tmp = new JSONObject();
						Canton canton = recommends.next();
						tmp.put(CODE, canton.getCode()); 
						tmp.put(NAME, canton.getName());
						array.put(tmp);
					}
					index.put(HOT);
					citys.put(HOT, array);
					
					for(int i=0; i<INDEX_KEY.length; i++){
						String indexHql = "from Canton as canton where canton.index = :index";
						query = session.createQuery(indexHql);
						query.setParameter("index", INDEX_KEY[i].toLowerCase());
						Iterator<Canton> cantons = query.iterate();
						if(cantons.hasNext()){
							array = new JSONArray(); 
							while( cantons.hasNext() ){
								JSONObject tmp = new JSONObject();
								Canton canton = cantons.next();
								tmp.put(CODE, canton.getCode()); 
								tmp.put(NAME, canton.getName());
								array.put(tmp);
							}
							index.put(INDEX_KEY[i]);
							citys.put(INDEX_KEY[i], array);
						}
					}
					citys.put(INDEX, index);
				}catch (Exception e) {
					e.printStackTrace();
					t.rollback();
				}finally{
					session.close();
				}
				curCitys = citys;
			}else{
				citys = curCitys;
			}
			resp.appendRespContent(CITYS, citys);
			resp.appendRespContent(VERSION, Config.CITY_VER);
		}else{
			resp.appendRespContent(VERSION, Config.CITY_VER);
		}
	}

}
